package com.example.myimageshare.adapter;

import android.content.Context;
import android.graphics.Point;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.myimageshare.R;
import com.example.myimageshare.Utils.ImageUtil;
import com.example.myimageshare.Utils.SizeUtil;
import com.example.myimageshare.View.MainActivity;
import com.example.myimageshare.domain.User;
import com.example.myimageshare.domain.UserArt;
import com.example.myimageshare.entity.PhotoItem;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadBatchListener;
import io.reactivex.annotations.NonNull;

public class ResultListAdapter extends RecyclerView.Adapter<ResultListAdapter.InnerHolder> {

    public static final String TAG = "ResultListAdapter";
    //上下文
    private Context context;

    private List<PhotoItem> mPhotoItems = new ArrayList<>();
    private int spanCount;

    @NonNull
    @Override
    public InnerHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_upload_photo, viewGroup, false);
        final  InnerHolder innerHolder = new InnerHolder(itemView);
        return innerHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull InnerHolder innerHolder,final int i) {
        View itemView = innerHolder.itemView;
        // 因为RecyclerView复用的问题，当条目个数比较上一次小的时候，是不会走onCreateViewHolder的，但肯定会走
        // onBindViewHolder,所以把屏幕适配的代码挪到这里来
        final Point point = SizeUtil.getScreenSize(itemView.getContext());
        Log.d(TAG, "screen width --> "+point.x);
        Log.d(TAG, "screen height --> "+point.y);
        Log.d(TAG, "span count --> " + spanCount);
        // 让单个条目宽高一致
        RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(
                point.x/spanCount, point.x/spanCount);
        itemView.setLayoutParams(layoutParams);
        if(innerHolder.ivDelete != null){
            innerHolder.ivDelete.setTag(i);
            innerHolder.ivDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = (int) v.getTag();

                    mPhotoItems.remove(position);
                    notifyDataSetChanged();
                }
            });
        }

        ImageView imageItem = itemView.findViewById(R.id.iv_images_upload);

        // 1. 实现Glide图片加载框架加载图片
        Glide.with(imageItem.getContext()).clear(imageItem);
        Glide.with(imageItem.getContext())
                .load(mPhotoItems.get(i)
                        .getPath())
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(imageItem);
    }

    public void uploadImgs(final UserArt user){
        final String[] filePaths = ImageUtil.getPaths(mPhotoItems);
        BmobFile.uploadBatch(filePaths, new UploadBatchListener() {

            @Override
            public void onSuccess(List<BmobFile> files,List<String> urls) {
                //1、files-上传完成后的BmobFile集合，
                // 是为了方便对其上传后的数据进行操作，例如可以将该文件保存到表中
                //2、urls-上传文件的完整url地址
                if(urls.size()==filePaths.length){//如果数量相等，则代表文件全部上传完成
                    //do something
                    setUserArt(urls,user);
                    Log.d("Upload","success");
                    Toast.makeText(context,"上传完成！",
                            Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(int statuscode, String errormsg) {
                Log.d("Upload", "Error");
            }

            @Override
            public void onProgress(int curIndex, int curPercent, int total,int totalPercent) {
                //1、curIndex--表示当前第几个文件正在上传
                //2、curPercent--表示当前上传文件的进度值（百分比）
                //3、total--表示总的上传文件数
                //4、totalPercent--表示总的上传进度（百分比）
                Toast.makeText(context,curPercent+"/"+totalPercent,
                        Toast.LENGTH_SHORT).show();
            }
        });
    }


    private void setUserArt(List<String> urls,final UserArt user){
        user.setUrls(urls);
        user.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if(e==null) {
                    Log.d("savaUserArtInfo", "succeess"+ s);
                    BmobQuery<UserArt> bmobQuery = new BmobQuery<UserArt>();
                    bmobQuery.getObject( s , new QueryListener<UserArt>() {
                        @Override
                        public void done(UserArt object,BmobException e) {
                            if(e==null){
                                Log.d("savaUserArtInfo", "查询成功");
                            }else{
                                Log.d("savaUserArtInfo", "查询失败");
                            }
                        }
                    });
                }else {
                    Log.d("savaUserArtInfo", "error:"+e);

                }
            }
        });
    }


//    private OnItemClickListener itemClickListener = null;
//    //接口暴露
//    public void setItemRemove(OnItemClickListener itemClickListener){
//        this.itemClickListener = itemClickListener;
//
//    }
//    public interface OnItemClickListener {
//        void onDelete(int position);
//    }

    @Override
    public int getItemCount() {
        return mPhotoItems.size();
    }

    public void setData(List<PhotoItem> photoItems, int spanCount, Context context) {
        this.context = context;
        this.spanCount = spanCount;
        mPhotoItems.clear();
        mPhotoItems.addAll(photoItems);
        notifyDataSetChanged();
    }

    public class InnerHolder extends RecyclerView.ViewHolder {
        ImageView ivDelete;
        public InnerHolder(@NonNull View itemView) {
            super(itemView);
            ivDelete = itemView.findViewById(R.id.bt_remove);

        }
    }
}